package com.github.slprj.slake.net;

import com.github.slprj.slake.pb.PbUtil;

import java.nio.ByteBuffer;

/**
 * @author YangXiaoLong
 * 2022/9/17 10:26
 */
public class ByteBufferWriteFrame extends WriteFrame {
    //扩展点
    private ByteBuffer body;
    private int bodySize = -1;

    public void setBody(ByteBuffer body) {
        this.body = body;
    }

    @Override
    protected int bodySize() {
        int bodySize = this.bodySize;
        if (bodySize == -1) {
            ByteBuffer body = this.body;
            bodySize = body == null ? 0 : body.remaining();
            this.bodySize = bodySize;
        }
        return bodySize;
    }

    @Override
    protected void encodeBody(ByteBuffer buf) {
        int bs = bodySize();
        if (bs > 0) {
            PbUtil.writeTag(buf, PbUtil.TYPE_LENGTH_DELIMITED, Frame.IDX_BODY);
            PbUtil.writeVarUnsignedInt32(buf, bs);
            //标记
            body.mark();
            //将body的数据读取到buf中
            buf.put(body);
            //恢复标记
            body.reset();
        }
    }
}
